﻿var OK = "OK";
var KO = "KO";

var jPlace = null;
var admUser = "";
var currentTab = -1;
var bPlaceFormInit = false;
	
var oPlacesTable = null;

function initDialogs() {
	$("#dialog-form").dialog({
		autoOpen : false,
		height : "auto",
		width : "90%",
		modal : true,
		buttons : {
			"Save" : function() {
				$('#placeForm').validate();
				if (!$('#placeForm').valid()) {
					return false;
				}
				updatePlace();
			},
			Cancel : function() {
				$(this).dialog("close");
			}
		},
		close : function(ev, ui) {

		}
	});

	$("#loadingScreen").dialog({
		autoOpen : false, // set this to false so we can manually open it
		dialogClass : "loadingScreenWindow",
		closeOnEscape : false,
		draggable : false,
		width : 460,
		minHeight : 50,
		modal : true,
		buttons : {},
		resizable : false,
		open : function() {
			$('body').css('overflow', 'hidden');
		},
		close : function() {
			$('body').css('overflow', 'auto');
		}
	});
}

function loadGeneralTab(index) {
	switch (index) {
	case 0:
		displayTablePlaces();
		break;
	case 1:
		break;
	case 2:
		break;
	case 3:
		break;
	case 4:
		break;
	}
}


function showMap(latitude, longitude) {
	var strMapPattern = "http://maps.google.com/maps/api/staticmap?center={0},{1}&zoom=16&size=102x102&maptype=roadmap&markers=color:red|{0},{1}&sensor=false";

	if (isNaN(latitude) || isNaN(longitude)) {
		$("#map").attr("src", "");
		$("#map").hide();
	} else {
		$("#map").attr("src", strMapPattern.format(latitude, longitude));
		$("#map").show();
	}
}

function generateThumbStreetView(urlStreetView) {
	var latitude;
	var longitude;

	var cbll;
	var acbll;
	var cbp;
	var acbp;
	var panhead;
	var panzoom;
	var panpitch;

	cbll = gup(urlStreetView, "cbll");
	acbll = cbll.split(",");
	latitude = acbll[0];
	longitude = acbll[1];
	cbp = gup(urlStreetView, "cbp");
	acbp = cbp.split(",");
	panhead = parseFloat(acbp[0] != "" ? acbp[0] : 34);
	panzoom = parseFloat(acbp[1] != "" ? acbp[1] : 1);
	panpitch = parseFloat(acbp[2] != "" ? acbp[2] : 5);
	console.log("panhead:" + panhead);
	console.log("panzoom:" + panzoom);
	console.log("panpitch:" + panpitch);
	var panpos = new google.maps.LatLng(latitude, longitude);
	var panoramaOptions = {
		position : panpos,
		pov : {
			heading : panhead,
			pitch : panpitch,
			zoom : panzoom
		}
	};
	$("#placeImage").empty();

	var myPano = new google.maps.StreetViewPanorama(document
			.getElementById("placeImage"), panoramaOptions);
	google.maps.event.trigger(myPano, 'resize');
}

function getPlace(codPlace) {
	waitingDialog({
		title : "Loading Place " + codPlace,
		message : "Please wait..."
	});
	$.post("/adm", {
		action : "getPlace",
		arg0 : codPlace
	}, onGetPlace)
}

function onGetPlace(response) {
	closeWaitingDialog();
	if (response == null) {
		$.jGrowl("response null", {
			header : 'Error Getting Place',
			life : 5000
		});
		return;
	}
	if (response.status == OK) {
		jPlace = response.results[0];
		showPlace();
	} else {
		$.jGrowl("response null", {
			header : 'Error Getting Place',
			life : 5000
		});
		return;
	}
}

function updatePlace() {
	waitingDialog({
		title : "Updating Place " + jPlace.codplace,
		message : "Please wait..."
	});
	// waitingDialog({title:"Loading Place " + codPlace});
	$.post("/adm", {
		action : "updatePlace",
		arg0 : $("#codplace").val(),
		arg1 : $("#name").val(),
		arg2 : $("#description").val(),
		arg3 : $("#type").val(),
		arg4 : $("#status").val(),
		arg5 : $("#categorytype").val(),
		arg6 : $("#latitude").val(),
		arg7 : $("#longitude").val(),
		arg8 : $("#urlStreetView").val(),
		arg9 : $("#url").val(),
		arg10 : $("#urlLogo").val(),
		arg11 : admUser
	}, onUpdatePlace)
}

function onUpdatePlace(response) {
	closeWaitingDialog();
	if (response == null) {
		$.jGrowl("response null", {
			header : 'Error Saving Place',
			life : 5000
		});
		return;
	}
	if (response.status == OK) {
		$.jGrowl("Place Saved", {
			header : 'Place ' + jPlace.codplace,
			life : 3000
		});
		$("#dialog-form").dialog('close');
		setTimeout('document.location.href = document.location.href', 3500);

	} else {
		$.jGrowl("response null", {
			header : 'Error Saving Place',
			life : 5000
		});
		return;
	}
}

function showPlaceImage() {
	$("#placeImage").removeAttr("style")
	$("#placeImage").css('border', '1 solid');
	$("#placeImage").css('width', '425px');
	$("#placeImage").css('height', '240px');
	$("#placeImage").empty();
	if ($("#urlStreetView").val().length > 0) {
		if ($("#urlStreetView").val().indexOf("http://maps.google") > -1)
			generateThumbStreetView($("#urlStreetView").val());
	} else {
		if ($("#urlLogo").val().length > 0)
			$("#placeImage").append(
					"<img src='" + $("#urlLogo").val()
							+ "' width='425' height='240'>")
	}
}

function showPlace() {
	if (!bPlaceFormInit)
	{
		bPlaceFormInit = true;      
        $("#latitude").change(function () {showMap($("#latitude").val(),$("#longitude").val()); });
        $("#longitude").change(function (){showMap($("#latitude").val(),$("#longitude").val()); });
        $("#urlLogo").change(function (){showPlaceImage();});
        $("#urlStreetView").change(function (){showPlaceImage();});            
        $("#placeForm").validate({
            rules: {
                name: {
                    required: true,
                    minlength: 5
                },            			            			
                description: {
                    required: true,
                    maxlength: 455
                },
                latitude: {
                    required: true,
                    number:true,
                    range: [-90,90]
                },
                longitude: {
                    required: true,
                    number: true,
                    range:[-180,180]
                },
                urlLogo:
                    {
                    url: true
                },
                urlStreetView:
                    {
                    url: true
                },
                url:
                    {
                    url: true
                }
            },
            messages: {
                latitude: 
                    {
                    number: "Please enter a valid latitude",
                    range: "Please enter a valid latitude between -90 and 90"
                },
                longitude: 
                    {
                    number: "Please enter a valid longitude",
                    range: "Please enter a valid latitude between -180 and 180"
                }            			
            }
        });    
	}
	
	for ( var key in jPlace) {
		fill(key);
	}
	showPlaceImage();
	showMap($("#latitude").val(), $("#longitude").val());

	$("#place-tabs").tabs({
		cookie : {
			// store cookie for a day, without, it would be a session cookie
			expires : 1
		}
	});

	$("#dialog-form").dialog('open');

}

function fill(name) {
	var tagName = $("#" + name)[0] == undefined ? "" : $("#" + name)[0].tagName;
	if (tagName == "")
		return;
	var encoded = eval("jPlace." + name);
	var decoded = $('<textarea />').html(encoded).val();
	$("#" + name).val(decoded);
}

function waitingDialog(waiting) { // I choose to allow my loading screen
	// dialog to be customizable, you don't have
	// to
	$("#loadingScreen").html(
			waiting.message && '' != waiting.message ? waiting.message
					: 'Please wait...');
	$("#loadingScreen").dialog('option', 'title',
			waiting.title && '' != waiting.title ? waiting.title : 'Loading');
	$("#loadingScreen").dialog('open');
}
function closeWaitingDialog() {
	$("#loadingScreen").dialog('close');
}

function displayTablePlaces() {
	if (oPlacesTable != null) {
		console.log("borro tabla");
		oPlacesTable.fnClearTable();
	} else {

		$("#places_list tbody").click(function(event) {

			$(oPlacesTable.fnSettings().aoData).each(function() {
				$(this.nTr).removeClass('row_selected');
			});
			$(event.target.parentNode).addClass('row_selected');
		});

		$("#places_list tbody td").live("click", function(event) {
			aPos = oPlacesTable.fnGetPosition(this);
			aData = oPlacesTable.fnGetData(aPos[0]);
			getPlace(aData[0]);
		});

		oPlacesTable = $('#places_list').dataTable({
			"bStateSave" : true,
			"bPaginate" : true,
			"bSort" : true,
			"bProcessing" : true,
			"bServerSide" : true,
			"bJQueryUI" : true,
			"sAjaxSource" : "/adm?action=getPlaces",
			"sPaginationType" : "full_numbers",
			"fnInitComplete" : function() {

			},
			"aoColumns" : [ {
				"bSearchable" : false,
				"bSortable" : false
			}, // CodPlace
			null, // Name
			{
				"bSearchable" : false
			}, // Description
			{
				"bSearchable" : false
			}, // Type
			{
				"bSearchable" : false
			}, // Category Type
			{
				"bSearchable" : false
			}, // Created by
			{
				"bSearchable" : false
			} // Creation
			]
		});
	}
}

function gup(url, name) {
	name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
	var regexS = "[\\?&]" + name + "=([^&#]*)";
	var regex = new RegExp(regexS);
	var results = regex.exec(url);
	if (results == null)
		return "";
	else
		return results[1];
}

// GENERIC STRING FORMAT
// String.format
function _StringFormatInline() {
	var txt = this;
	for ( var i = 0; i < arguments.length; i++) {
		var exp = new RegExp('\\{' + (i) + '\\}', 'gm');
		txt = txt.replace(exp, arguments[i]);
	}
	return txt;
}

function _StringFormatStatic() {
	for ( var i = 1; i < arguments.length; i++) {
		var exp = new RegExp('\\{' + (i - 1) + '\\}', 'gm');
		arguments[0] = arguments[0].replace(exp, arguments[i]);
	}
	return arguments[0];
}

if (!String.prototype.format) {
	String.prototype.format = _StringFormatInline;
}

if (!String.format) {
	String.format = _StringFormatStatic;
}
